import React from 'react';
import { connect } from 'umi';
import { Form, Input, Button, Select, Card, DatePicker, message, TreeSelect, Spin, Divider } from 'antd';
import { formatMessage } from 'umi';
import { history } from 'umi';
import moment from 'moment';
import { eventTrack } from '@/utils/track';
import { get as _get } from 'object-path';
import CascaderLoad from '@/components/CascaderLoad';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { queryCompany } from '@/services/user';
import { BottomAction } from '@/components';
import { withRoutePage } from '@/utils/enhanceUtils';

import styles from './OrgList.less';

const FormItem = Form.Item;
const { Option } = Select;
const { TreeNode } = TreeSelect;
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 8 }
    }
};

// [DELETE这个页面应该可以删除了，属于旧的组织机构]

@withRoutePage
@connect(({ orgManage, dictionary, loading }) => ({
    orgManage,
    dictionary,
    loading: loading.global
}))
@Form.create()
class OrgEdit extends React.PureComponent {
    state = {};

    componentDidMount() {
        const {
            location: { query },
            dispatch
        } = this.props;

        // 获取公司下拉树
        dispatch({
            type: 'orgManage/fetchOrgTree'
        });

        dispatch({
            type: 'orgManage/fetchRegionalLeader',
            payload: {
                companyId: 100
            }
        });

        dispatch({
            type: 'dictionary/fetchDictionaryList',
            payload: {
                codes: ['asian', 'industryType']
            }
        });

        const { id } = query;
        if (id) {
            dispatch({
                type: 'orgManage/fetchOrgInfo',
                payload: {
                    id
                }
            });
        }
    }

    handleSave = () => {
        const {
            dispatch,
            form,
            location: { query }
        } = this.props;
        const { id = null } = query;
        form.validateFieldsAndScroll((err, fieldsValue) => {
            if (err) return;

            const regTime = _get(fieldsValue, 'regTime');
            let regTimeStr = '';
            if (regTime) {
                regTimeStr = regTime.format('YYYY-MM-DD');
            }
            // 行业特殊处理
            let industry = _get(fieldsValue, 'industry');
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            let eventName = 'organization_orgList_creat_submit_click';
            if (industry === undefined) {
                industry = null;
            }
            if (id) {
                eventName = 'organization_orgList_edit_submit_click';
            }
            dispatch({
                type: 'orgManage/saveOrgInfo',
                payload: {
                    ...fieldsValue,
                    regTime: regTimeStr,
                    id,
                    industry
                },
                callback: async res => {
                    if (res.code === 10000) {
                        message.success(res.msg);
                        // 修改公司后需要更新右上角公司列表信息
                        const result = await queryCompany();
                        if (result.code === 10000) {
                            localStorage.setItem('companys', JSON.stringify(result.data));
                            // 埋点
                            await eventTrack({
                                eventName,
                                eventProps: { status: 0 }
                            });
                            history.push({
                                pathname: '/office/personnelManagement/organization/orgList'
                            });
                        } else {
                            message.error(res.msg);
                            // 埋点
                            await eventTrack({
                                eventName,
                                eventProps: { status: 1, error_info: res.msg }
                            });
                        }
                    } else {
                        message.error(res.msg);
                        // 埋点
                        eventTrack({
                            eventName,
                            eventProps: { status: 1, error_info: res.msg }
                        });
                    }
                }
            });
        });
    };

    handleCancel = async () => {
        const {
            location: { query }
        } = this.props;
        const { id = null } = query;
        // 埋点
        await eventTrack({
            eventName: id ? 'organization_orgList_edit_cancel_click' : 'organization_orgList_creat_cancel_click'
        });
        history.push({
            pathname: '/office/personnelManagement/organization/orgList'
        });
    };

    render() {
        const {
            form: { getFieldDecorator },
            location: { query },
            orgManage: { orgInfo, orgTree, regionalLeader },
            dictionary: { industryType },
            loading
        } = this.props;
        const { id } = query;

        const renderOption = data =>
            data.map(item => (
                <Option key={item.dictValue} value={item.dictValue}>
                    {item.dictName}
                </Option>
            ));

        const leaderOption = (data = []) =>
            data.map(item => (
                <Option key={item.employeeName} value={item.id}>
                    {item.employeeName}
                </Option>
            ));

        const renderTreeNodes = data =>
            data.map(item => {
                if (item.children) {
                    return (
                        <TreeNode
                            title={_get(item, 'companyName')}
                            key={_get(item, 'id')}
                            value={_get(item, 'id')}
                            dataRef={item}
                        >
                            {renderTreeNodes(_get(item, 'children'))}
                        </TreeNode>
                    );
                }
                return <TreeNode key={_get(item, 'id')} title={_get(item, 'companyName')} value={_get(item, 'id')} />;
            });

        const renderFileId = () =>
            getFieldDecorator('parentId', {
                initialValue: _get(orgInfo, 'parentId', null)
            })(<Input hidden />);

        const renderFileName1 = () =>
            getFieldDecorator('parentName', {
                initialValue: _get(orgInfo, 'parentName', null),
                rules: [
                    {
                        required: true,
                        message: formatMessage({
                            id: 'msg.orgEdit.parentOrg.required'
                        })
                    }
                ]
            })(<Input disabled />);

        const renderFileName2 = () =>
            getFieldDecorator('parentId', {
                initialValue: id && _get(orgInfo, 'parentId', null) ? _get(orgInfo, 'parentId', null) : null,
                rules: [
                    {
                        required: true,
                        message: formatMessage({
                            id: 'msg.orgEdit.parentOrg.required'
                        })
                    }
                ]
            })(
                <TreeSelect
                    showSearch
                    placeholder={formatMessage({
                        id: 'placeHolder.orgEdit.orgIndustry'
                    })}
                    treeDefaultExpandedKeys={orgTree && orgTree.length > 0 ? [`${orgTree[0].id}`] : []}
                    allowClear
                    treeDefaultExpandAll
                    treeNodeFilterProp="title"
                >
                    {renderTreeNodes(orgTree)}
                </TreeSelect>
            );

        return (
            <PageHeaderWrapper>
                <Spin spinning={loading}>
                    <Card bordered={false}>
                        <Form layout="horizontal" {...formItemLayout}>
                            <div className={styles.orgEditInfoTitle}>
                                {formatMessage({
                                    id: 'label.orgEdit.orgInfo'
                                })}
                            </div>
                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgName'
                                })}
                                extra={formatMessage({
                                    id: 'extra.orgEdit.orgName'
                                })}
                            >
                                {getFieldDecorator('companyName', {
                                    initialValue:
                                        id && _get(orgInfo, 'companyName', null) ? _get(orgInfo, 'companyName') : '',
                                    rules: [
                                        {
                                            required: true,
                                            message: formatMessage({
                                                id: 'msg.orgEdit.orgName.required'
                                            })
                                        },
                                        {
                                            min: 2,
                                            max: 50,
                                            message: formatMessage({
                                                id: 'msg.orgEdit.orgName.length'
                                            })
                                        }
                                    ]
                                })(
                                    <Input
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgName'
                                        })}
                                    />
                                )}
                            </FormItem>
                            <Form.Item style={{ display: 'none' }}>{id ? renderFileId() : null}</Form.Item>
                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.parentOrg'
                                })}
                            >
                                {id ? renderFileName1() : renderFileName2()}
                            </FormItem>
                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgEmail'
                                })}
                            >
                                {getFieldDecorator('companyEmail', {
                                    initialValue:
                                        id && _get(orgInfo, 'companyEmail', null)
                                            ? _get(orgInfo, 'companyEmail', null)
                                            : '',
                                    rules: [
                                        {
                                            required: true,
                                            message: formatMessage({
                                                id: 'msg.orgEdit.companyEmail.required'
                                            })
                                        },
                                        {
                                            type: 'email',
                                            message: formatMessage({
                                                id: 'msg.orgEdit.companyEmail.format'
                                            })
                                        }
                                    ]
                                })(
                                    <Input
                                        type="email"
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgEmail'
                                        })}
                                    />
                                )}
                            </FormItem>
                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgCorporation'
                                })}
                            >
                                {getFieldDecorator('legalRepresentative', {
                                    initialValue:
                                        id && _get(orgInfo, 'legalRepresentative', null)
                                            ? _get(orgInfo, 'legalRepresentative', null)
                                            : ''
                                })(
                                    <Input
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgCorporation'
                                        })}
                                    />
                                )}
                            </FormItem>
                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.chairman'
                                })}
                            >
                                {getFieldDecorator('chairmanId', {
                                    initialValue: id ? _get(orgInfo, 'chairmanId', null) : null
                                })(
                                    <Select
                                        showSearch
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.chairman'
                                        })}
                                        allowClear
                                        filterOption={(input, option) =>
                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {leaderOption(regionalLeader)}
                                    </Select>
                                )}
                            </FormItem>
                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgManager'
                                })}
                            >
                                {getFieldDecorator('companyManagerId', {
                                    initialValue:
                                        id && _get(orgInfo, 'companyManagerId', null)
                                            ? _get(orgInfo, 'companyManagerId', null)
                                            : ''
                                })(
                                    <Select
                                        showSearch
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgIndustry'
                                        })}
                                        allowClear
                                        filterOption={(input, option) =>
                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {leaderOption(regionalLeader)}
                                    </Select>
                                )}
                            </FormItem>
                            <Divider style={{ margin: '32px 0' }} />
                            <div className={styles.orgEditInfoTitle}>
                                {formatMessage({
                                    id: 'label.orgEdit.contactInfo'
                                })}
                            </div>
                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgRegion'
                                })}
                            >
                                {getFieldDecorator('companyArea', {
                                    initialValue:
                                        id && _get(orgInfo, 'companyArea', '')
                                            ? _get(orgInfo, 'companyArea', '').split(',')
                                            : null,
                                    rules: [
                                        {
                                            required: true,
                                            message: formatMessage({
                                                id: 'msg.orgEdit.orgRegion.required'
                                            })
                                        }
                                    ]
                                })(
                                    <CascaderLoad
                                        cascaderProps={{
                                            placeholder: formatMessage({
                                                id: 'placeHolder.orgEdit.orgRegion'
                                            })
                                        }}
                                        // asianData={asian}
                                    />
                                )}
                            </FormItem>

                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgAddress'
                                })}
                            >
                                {getFieldDecorator('companyAddress', {
                                    initialValue:
                                        id && _get(orgInfo, 'companyAddress', null)
                                            ? _get(orgInfo, 'companyAddress', null)
                                            : ''
                                })(
                                    <Input
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgAddress'
                                        })}
                                    />
                                )}
                            </FormItem>

                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgPhone'
                                })}
                            >
                                {getFieldDecorator('companyPhone', {
                                    initialValue:
                                        id && _get(orgInfo, 'companyPhone', null)
                                            ? _get(orgInfo, 'companyPhone', null)
                                            : '',
                                    rules: [
                                        {
                                            pattern: /^[0-9-]+$/,
                                            message: '只能输入数字、-'
                                        },
                                        {
                                            max: 50,
                                            message: '只能输入50位'
                                        }
                                    ]
                                })(
                                    <Input
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgPhone'
                                        })}
                                    />
                                )}
                            </FormItem>
                            <Divider style={{ margin: '32px 0' }} />
                            <div className={styles.orgEditInfoTitle}>
                                {formatMessage({
                                    id: 'label.orgEdit.basicInfo'
                                })}
                            </div>

                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgLicense'
                                })}
                            >
                                {getFieldDecorator('licenseCode', {
                                    initialValue:
                                        id && _get(orgInfo, 'licenseCode', null)
                                            ? _get(orgInfo, 'licenseCode', null)
                                            : ''
                                })(
                                    <Input
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgLicense'
                                        })}
                                    />
                                )}
                            </FormItem>

                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgCreateTime'
                                })}
                            >
                                {getFieldDecorator('regTime', {
                                    initialValue:
                                        id && _get(orgInfo, 'regTime', null) ? moment(_get(orgInfo, 'regTime')) : null,
                                    rules: [
                                        {
                                            required: true,
                                            message: formatMessage({
                                                id: 'msg.orgEdit.regTime.required'
                                            })
                                        }
                                    ]
                                })(
                                    <DatePicker
                                        style={{ width: '100%' }}
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgCreateTime'
                                        })}
                                    />
                                )}
                            </FormItem>

                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgMainBusiness'
                                })}
                            >
                                {getFieldDecorator('business', {
                                    initialValue:
                                        id && _get(orgInfo, 'business', null) ? _get(orgInfo, 'business', null) : ''
                                })(
                                    <Input
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgMainBusiness'
                                        })}
                                    />
                                )}
                            </FormItem>

                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgIndustry'
                                })}
                            >
                                {getFieldDecorator('industry', {
                                    initialValue: id && _get(orgInfo, 'industry', undefined)
                                })(
                                    <Select
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgIndustry'
                                        })}
                                        allowClear
                                    >
                                        {renderOption(industryType)}
                                    </Select>
                                )}
                            </FormItem>

                            <FormItem
                                label={formatMessage({
                                    id: 'label.orgEdit.orgIntroduction'
                                })}
                            >
                                {getFieldDecorator('introduce', {
                                    initialValue:
                                        id && _get(orgInfo, 'introduce', null) ? _get(orgInfo, 'introduce', null) : ''
                                })(
                                    <Input.TextArea
                                        rows={4}
                                        placeholder={formatMessage({
                                            id: 'placeHolder.orgEdit.orgIntroduction'
                                        })}
                                    />
                                )}
                            </FormItem>

                            <BottomAction>
                                <Button type="primary" onClick={this.handleSave}>
                                    {formatMessage({
                                        id: 'btn.orgEdit.save'
                                    })}
                                </Button>
                                <Button loading={loading} style={{ marginLeft: '20px' }} onClick={this.handleCancel}>
                                    {formatMessage({
                                        id: 'btn.orgEdit.cancel'
                                    })}
                                </Button>
                            </BottomAction>
                        </Form>
                    </Card>
                </Spin>
            </PageHeaderWrapper>
        );
    }
}

export default OrgEdit;
